package com.controller;

import com.controller.param.UserInfo;
import com.controller.param.WxResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.sql.Statement;

@Slf4j
@RequestMapping()
@RestController
public class LoginController {

    public RestTemplate restTemplate;

    public LoginController(){
         restTemplate = new RestTemplate();
    }

    @Autowired
    JdbcTemplate jdbcTemplate;

    @RequestMapping(value = "getUserInfo",method = RequestMethod.POST)
    public String getUserInfo(UserInfo userInfo){
        // save UserInfo 使用 加密数据解密算法 get openId ,and to association.
        Boolean execute = jdbcTemplate.execute((Statement stmt) -> {
            String format = String.format("update users set nickname=%s where openId=%s",userInfo.getNickname(),userInfo.getOpenId());
            return stmt.execute(format);
        });
        return "";
    }

    @RequestMapping(value = "onLogin",method = RequestMethod.GET)
    public String onLogin(String code){
        String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=%s&grant_type=authorization_code", code);
        WxResponse wxResponse = this.restTemplate.getForObject(url, WxResponse.class);
        Boolean execute = jdbcTemplate.execute((Statement stmt) -> {
            String format = String.format("insert into users(openId,unionId) values(%s,%s)", wxResponse.getOpenId(), wxResponse.getUnionId());
            return stmt.execute(format);
        });
        if(execute){
            return "yes";
        }else{
            return "no";
        }
    }

    @RequestMapping("/s/login")
    public String login(@RequestParam(value = "username")String user,@RequestParam(value = "password")String pwd){
        // wx authentication method.
        // frontend use openId to login userInfo .
        UsernamePasswordToken token = new UsernamePasswordToken(user,pwd,true);
        try {
            SecurityUtils.getSubject().login(token);
        } catch (AuthenticationException e) {
            log.debug("Error authenticating.", e);
        }
        return "hcj";
    }


}
